<template>
  <div>
    <van-nav-bar title="栏目管理" left-arrow @click-left="onClickLeft" />
    <h1>点击删除频道</h1>
    <van-grid :gutter="8" :column-num="4">
      <van-grid-item
        v-for="(value, index) in categoryList"
        :key="value.id"
        :text="value.name"
        @click="removeFn(index)"
      />
    </van-grid>
    <h1>点击添加频道</h1>
    <van-grid :gutter="8" :column-num="4">
      <van-grid-item
        v-for="(value, index) in delCategoryList"
        :key="value.id"
        :text="value.name"
        @click="addFn(index)"
      />
    </van-grid>
  </div>
</template>

<script>
import { category } from "@/apis/get";
export default {
  data() {
    return {
      categoryList: [],
      delCategoryList: [],
      defaultCategoryList: [],
    };
  },
  created() {
    if (localStorage.getItem("categoryList")) {
      this.categoryList = JSON.parse(localStorage.getItem("categoryList"));
      this.delCategoryList = JSON.parse(
        localStorage.getItem("delCategoryList")
      );
      this.defaultCategoryList = JSON.parse(
        localStorage.getItem("defaultCategoryList")
      );
      return;
    }
    category().then((res) => {
      if (localStorage.getItem("token")) {
        this.defaultCategoryList = res.data.data.slice(0, 2);
        this.categoryList = res.data.data.slice(2);
      } else {
        this.defaultCategoryList = res.data.data.slice(0, 1);
        this.categoryList = res.data.data.slice(1);
      }
    });
  },
  methods: {
    // 返回个人中心
    onClickLeft() {
      this.$router.push({
        path: "index",
      });
    },
    addFn(index) {
      this.categoryList.push(this.delCategoryList.splice(index, 1)[0]);
    },
    removeFn(index) {
      this.delCategoryList.push(this.categoryList.splice(index, 1)[0]);
    },
  },
  watch: {
    deep: true,
    categoryList(newVal, oldVal) {
      localStorage.setItem("categoryList", JSON.stringify(this.categoryList));
      localStorage.setItem(
        "delCategoryList",
        JSON.stringify(this.delCategoryList)
      );
      localStorage.setItem(
        "defaultCategoryList",
        JSON.stringify(this.defaultCategoryList)
      );
    },
  },
};
</script>

<style>
</style>